package com.lbs.jiepiaisi.utils;

import android.util.Log;

import com.google.gson.Gson;
import com.lbs.jiepiaisi.base.BaseResponseEntity;
import com.lbs.jiepiaisi.base.ResultException;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by yu on 2019-12-19 11:22.
 * Description: 自定义Gson响应体变换器
 */
public class GsonResponseBodyConverter <T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final Type type;

    public GsonResponseBodyConverter(Gson gson, Type type){
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        Log.e("response","result = "+response);
        //先将返回的json数据解析到Response中，如果code == 0，则解析到我们的实体基类中，否则抛异常
        BaseResponseEntity res = gson.fromJson(response, BaseResponseEntity.class);
        Log.e("convert","code = " + res.getCode());
        if (res.getCode() == 0){
//            Log.e("正常","code为0时，直接解析，不可能出现解析异常.");
            return gson.fromJson(response,type);
        } else {
            // 这样就可以获得json解析异常拿不到失败的状态码和提示信息了
//            Log.e("异常","抛一个自定义ResultException，传入失败时候的状态码和信息.");
            Log.e("异常","code = "+res.getCode()+"--"+"msg = "+res.getMsg());
            throw new ResultException(res.getMsg(),res.getCode());
        }
    }
}
